package JZ21_栈的压入弹出序列;

import java.util.ArrayList;
import java.util.Stack;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        ArrayList<Integer> pushedList = arrayToList(pushA);
        ArrayList<Integer> poppedList = arrayToList(popA);

        Stack<Integer> stack = new Stack<>();

        for (int e : poppedList){
            if (!stack.isEmpty() && stack.peek() == e){
                stack.pop();
                continue;
            }

            while (true){
                if (pushedList.isEmpty()){
                    return false;
                }
                int f = pushedList.remove(0);
                if (f != e){
                    stack.push(f);
                }else {
                    break;
                }
            }

        }
        return stack.isEmpty();
    }

    private ArrayList<Integer> arrayToList(int[] array) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int e : array){
            list.add(e);
        }
        return list;
    }
}